﻿# -*- coding:UTF-8 -*-

import os
import sys
import io
import time
from math import ceil

from collections import OrderedDict
import PyPDF3

import piexif

"""文件操作"""
class Opermeta:

    def __init__(self, data_path, type):
       self.data_path = data_path
       self.type = type
       sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')  # 解决不能再window编码问题

    def read(self):
        if self.type == 1:
            data = OrderedDict()
            file = os.stat(self.data_path) #读取文件数据
            data['文件大小'] = format(ceil(file.st_size/1024)) + "M"
            data['创建时间'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(file.st_ctime))
            data['访问时间'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(file.st_atime))
            data['修改时间'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(file.st_mtime))
            return data

        elif self.type == 2:
            file = open(self.data_path, 'rb')
            pdffile = PyPDF3.PdfFileReader(file)
            pdfInfo = pdffile.getDocumentInfo()
            print(pdfInfo)
            # for key in pdfInfo:
            #     print(key, ":", pdfInfo[key])
            exit()
        elif self.type == 3 :
            exif_dict = piexif.load(self.data_path)
            thumbnail = exif_dict.pop("thumbnail")
            if thumbnail is not None:
                with open("thumbnail.jpg", "wb+") as f:
                    f.write(thumbnail)
            for ifd_name in exif_dict:
                print("\n{0} IFD:".format(ifd_name))
                for key in exif_dict[ifd_name]:
                    try:
                        print(key, exif_dict[ifd_name][key][:10])
                    except:
                        print(key, exif_dict[ifd_name][key])



    def addMetadata(self, infos, data_save):
        """
        添加元素据
            Example: ``{u'/Title': u'My title'}``
        """
        file = open(self.data_path, 'rb')
        pdf_reader = PyPDF3.PdfFileReader(file)
        # 创建一个pdf文档，这个只是代表pdf文档的值，并没有创建实际的文档。
        pdf_writer = PyPDF3.PdfFileWriter()

        for pagenum in range(pdf_reader.numPages):
            pageobj = pdf_reader.getPage(pagenum)


            pdf_writer.addPage(pageobj)


        pdf_writer.addMetadata(infos)

        pdffile = open(data_save,'wb')
        pdf_writer.write(pdffile)
        return "修改成功"
